# -*- coding: utf-8 -*-
#
# Copyright (C) 2007, pysozluk-qt Development Team
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# Please read the COPYING file.
#

import urllib2
import BeautifulSoup
from database import Translation

class parser:
    def __init__(self, keyword, dicts="all"):
        self.word  = keyword
        self.fetch = 0

    def get(self):
        self.read()
        div = self.text.findAll("div")
        try:
            turkish, english = self.parse(str(div[1]),0), self.parse(str(div[3]),1)
        except IndexError:
            return None
        else:
            results = []
            for n in turkish:
                results.append(Translation((0,1, self.word, n)))
            for n in english:
                results.append(Translation((1,0, self.word, n)))
            return results

    def read(self):
        if not self.fetch:
            self.text = BeautifulSoup.RobustHTMLParser(unicode(urllib2.urlopen("http://www.seslisozluk.com/?word=%s" % self.word).read(), "cp1254"))
            self.text = self.text.find("table", width="100%", cellpadding="0", cellspacing="0", border="0", bgcolor="ffffff")
            self.fetch = 1

    def parse(self, variable, en):
        variable = variable.split("<b>")
        variable.remove(variable[0])
        try:
            variable[-1] = variable[-1].replace("</div>","")
        except IndexError:
            return None
        else:    
            results = []
            for n in variable:
                results.append(n[n.find("&nbsp;")+6:].replace("<br />",""))
            if en:
                try:
                    return results[4:]
                except:
                    return results
            else:
                return results
